package com.hhs.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.NotepadDao;
import com.hhs.storage.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.util.DateEasy;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-06-13
 */
@Service
public class NotepadServiceImpl extends ServiceImpl<NotepadDao, Notepad> implements NotepadService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private ProjectWorkFlowService workFlowService;
    @Resource
    private NotepadOtherService notepadOtherService;
    @Resource
    private NotepadDao notepadDao;
    @Resource
    private NotepadService notepadService;
    @Resource
    private ProjectWorkFlowService projectWorkFlowService;
    @Resource
    private ZrSimulateService zrSimulateService;
    @Resource
    private AttachmentListService attachmentListService;
    @Resource
    private ProjectPlanService projectPlanService;
    @Resource
    private BaseUserService userService;
    @SneakyThrows
    @Override
    public Map<String, Object> getAll(Notepad notepad, InputParam inputParam) {
        QueryWrapper<Notepad> qw = new QueryWrapper<>();
        //当前登录用户id
        String loginUserId="";
        if(!StringUtil.iszNull(inputParam.getUserId())){
            loginUserId=inputParam.getUserId();
        }else{
            loginUserId = SysUtil.getLoginUserId(request);
        }
        qw.eq("creater",loginUserId);
        //加入其它查询条件,全员计划的过滤用---start
        if(!StringUtil.iszNull(notepad.getContent())){
            qw.like("content",notepad.getContent());
        }
        if(!StringUtil.iszNull(notepad.getImportantFlag())){
            qw.eq("important_flag",notepad.getImportantFlag());
        }
        if(!StringUtil.iszNull(notepad.getState())){
            qw.eq("state",notepad.getState());
        }
        if(!StringUtil.iszNull(notepad.getCreateTime())){
            qw.ge("create_time",new DateEasy(notepad.getCreateTime()).toYYYYhMMhDDhHHcMMcSS());
        }
        if(!StringUtil.iszNull(inputParam.getMainId())){
            qw.eq("id",inputParam.getMainId());
        }
        //是否有工序信息
        if(!StringUtil.iszNull(notepad.getFlagWk())){
            //FIXME 没有完成
            if(notepad.getFlagWk()==true){
                qw.exists("SELECT * FROM project_work_flow WHERE `type`=1 AND project_plan_id='"+loginUserId+"-"+notepad.getId()+"'");
            }else{
                qw.notInSql("id","SELECT\n" +
                        "      notepad_id\n" +
                        "    FROM\n" +
                        "      notepad_other\n" +
                        "    WHERE data_json NOT LIKE '%\"subWk\":[]%'\n" +
                        "      AND data_json IS NOT NULL\n" +
                        "    UNION\n" +
                        "    SELECT\n" +
                        "      notepad_id\n" +
                        "    FROM\n" +
                        "      notepad_other\n" +
                        "     WHERE data_json NOT LIKE '%\"leaderWk\":[]%'\n" +
                        "      AND data_json IS NOT NULL\n" +
                        "    ");
            }
        }
        //是否有完整信
        if(!StringUtil.iszNull(notepad.getFlagFull())){
            if(notepad.getFlagFull()==true){
                qw.inSql("id","select notepad_id from notepad_other");
            }else{
                qw.notInSql("id","select notepad_id from notepad_other");
            }
        }
        //加入其它查询条件,全员计划的过滤用----end

        //加入条件，日历显示的时候用----start
        if(inputParam.getStartDate()!=null){
            qw.ge("create_time",new DateEasy(inputParam.getStartDate()).toYYYYhMMhDDhHHcMMcSS());
        }
        if(inputParam.getEndDate()!=null){
            qw.le("create_time",new DateEasy(inputParam.getEndDate()).toYYYYhMMhDDhHHcMMcSS());
        }
        //加入条件，日历显示的时候用----end
        if( StringUtils.isNotEmpty(inputParam.getRemark())) {
            qw.like("content", inputParam.getRemark());
        }
        if(inputParam.getStatus()!=null) {
            if(inputParam.getStatus()==5){
                qw.eq("important_flag",1);
            }else{
                qw.eq("state", inputParam.getStatus());
            }
        }
        if(!StringUtil.iszNull(notepad.getSearchTime())) {
            if(notepad.getSearchTime().length()==10){
                qw.eq("DATE(create_time)", new DateEasy(notepad.getSearchTime()).toYYYYhMMhDD());
            }
            if(notepad.getSearchTime().length()==4){
                qw.eq("YEAR(create_time)", notepad.getSearchTime());
            }
            if(notepad.getSearchTime().length()==7){
                qw.eq("YEAR(create_time)", notepad.getSearchTime().substring(0,4));
                qw.eq("MONTH(create_time)", notepad.getSearchTime().substring(5));
            }
        }
        if (inputParam.getStartDate()!=null&&inputParam.getEndDate()!=null){
            qw.between("create_time",inputParam.getStartDate(),
                    inputParam.getEndDate());
        }
        qw.orderByDesc("sort_key");
        qw.orderByDesc("create_time");//按时间倒序排序
        //分页查询
        Page<Notepad> result = this.page(new Page<Notepad>(
                inputParam.getPage(),
                inputParam.getSize()), qw);
        List<Notepad> list = result.getRecords();
        //填充内容
        for (Notepad temp : list) {
            hasWk(temp);
        }
        long total = result.getTotal();
        Map map = new HashMap();
        map.put("code", 1);
        map.put("rows", list);
        map.put("total", total);
        return map;
    }

    @SneakyThrows
    @Override
    public Map<String, Object> addOrUpdate(Notepad notepad,InputParam inputParam) {

        if (StringUtils.isEmpty(notepad.getContent())) {
            return ResponseInfo.error("内容不可为空");
        }
        //当前登录用户id
        String loginUserId="";
        if(!StringUtil.iszNull(inputParam.getUserId())){
            loginUserId=inputParam.getUserId();
        }else{
            loginUserId = SysUtil.getLoginUserId(request);
        }
        if (null==notepad.getId()) {
            notepad.setCreater(loginUserId);
            if(notepad.getCreateTimeStartTime()!=null){
                String str=new DateEasy(notepad.getCreateTimeStartTime()).toYYYYhMMhDD()+" "+new DateEasy().toHHcMMcSS();
                notepad.setCreateTime(new DateEasy(str).toLocalDateTime());
            }else{
                notepad.setCreateTime(LocalDateTime.now());
            }

            notepad.setState(0);
            //得到sortkey的最大值
            Integer maxSortKey=notepadDao.getMax();
            notepad.setSortKey(maxSortKey);
            System.out.println("最大值"+maxSortKey);
            this.save(notepad);
        }else{
            this.updateById(notepad);
        }
        return ResponseInfo.success( );
    }

    @Override
    public Map<String, Object> dele(Integer id) {
        if (id.equals(null)) {
            return ResponseInfo.error("参数错误");
        }
        QueryWrapper<Notepad> qw = new QueryWrapper<>();
        //当前登录用户id
        qw.eq("id",id);
        this.remove(qw);
        //删除关联项
        QueryWrapper<NotepadOther> qwnt=new QueryWrapper<>();
        qwnt.eq("notepad_id",id);
        notepadOtherService.remove(qwnt);
        return ResponseInfo.success( );
    }

    @Override
    public Map<String, Object> deleAll(InputParam inputParam) {
        QueryWrapper<Notepad> qw = new QueryWrapper<>();
        //当前登录用户id
        String loginUserId="";
        if(!StringUtil.iszNull(inputParam.getUserId())){
            loginUserId=inputParam.getUserId();
        }else{
            loginUserId = SysUtil.getLoginUserId(request);
        }
        qw.eq("creater",loginUserId);
        List<Notepad> list = this.list(qw);
        List<String> ids=new ArrayList<>();
        for (Notepad item : list) {
            ids.add(item.getId());
            this.deleFlowAndOther(item);
        }
        this.remove(qw);
        //删除关联项
        QueryWrapper<NotepadOther> qwnt=new QueryWrapper<>();
        qwnt.in("notepad_id",ids);
        notepadOtherService.remove(qwnt);
        return ResponseInfo.success();
    }
    @Override
    public Map<String, Object> complete(Integer id) {
        if (id.equals(null)) {
            return ResponseInfo.error("参数错误");
        }
        //当前登录用户id
//        String loginUserId = SysUtil.getLoginUserId(request);
        UpdateWrapper<Notepad> uw=new UpdateWrapper<>();
//        uw.eq("creater",loginUserId);
        uw.eq("state",0);
        uw.eq("id",id);
        uw.set("state",1);//状态
        uw.set("complete_time",LocalDateTime.now());
        this.update(uw);
        return ResponseInfo.success( );
    }

    @Override
    public Map<String, Object> remind(Notepad notepad) {
//        String loginUserId = SysUtil.getLoginUserId(request);
        UpdateWrapper<Notepad> uw=new UpdateWrapper<>();
//        uw.eq("creater",loginUserId);
        uw.eq("state",0);
        uw.eq("id",notepad.getId());
        uw.set("remind_date",notepad.getRemindDate());
        this.update(uw);
        return ResponseInfo.success( );
    }

    @Override
    public Map<String, Object> remindMe() {

        QueryWrapper<Notepad> qw = new QueryWrapper<>();
        //当前登录用户id
        String loginUserId = SysUtil.getLoginUserId(request);
        qw.eq("creater",loginUserId);
        qw.eq("state",0);//未完成
        qw.isNotNull("remind_date");
        qw.le("remind_date", LocalDate.now());
        qw.orderByDesc("create_time");//按时间倒序排序

        List<Notepad> list = this.list(qw);
        return  ResponseInfo.success( list);
    }

    @Override
    public Map<String, Object> wkEdit(Notepad notepad) {
        if (notepad.getId()==null || notepad.getSubWk()==null) {
            return ResponseInfo.error("参数错误");
        }
        //删除
        deleFlowAndOther(notepad);
        workFlowService.addWorkFlow(notepad.getId(),notepad.getSubWk(),4);
        return  ResponseInfo.success( );
    }
    /**
     * 删除多余的会签附件再加入
     * @param notepad
     */
    private void deleFlowAndOther(Notepad notepad) {
        QueryWrapper<ProjectWorkFlow> pw = new QueryWrapper<>();
        pw.eq("project_plan_id",notepad.getId());
        workFlowService.remove(pw);
        for(SubWkFlow swf:notepad.getSubWk()){
            for(ProjectWorkFlow projectWorkFlow:swf.getTableData()){
                //删除所有会签人再加入
                QueryWrapper qwhq=new QueryWrapper();
                qwhq.eq("flow_id", projectWorkFlow.getId());
                zrSimulateService.remove(qwhq);
                //删除所有附件列表
                QueryWrapper<AttachmentList> qwatta=new QueryWrapper<>();
                qwatta.eq("target_id",projectWorkFlow.getId());
                attachmentListService.remove(qwatta);
            }
        }
    }
    @Override
    public Map<String, Object> wkQuery(Notepad notepad) {
        if (notepad.getId()==null ) {
            return ResponseInfo.error("参数错误");
        }
        //查询工序
        QueryWrapper qw2 = new QueryWrapper<ProjectWorkFlow>();
        qw2.eq("project_plan_id", notepad.getId());
        qw2.isNull("user_id");
        qw2.orderByAsc("row_index");
        qw2.orderByAsc("step");
        List<ProjectWorkFlow> projectWorkFlowList = workFlowService.list(qw2);
        Map<Integer,List<ProjectWorkFlow>> map = new LinkedHashMap<>();
        for (int i = 0; i < projectWorkFlowList.size(); i++) {
            //设置节点的会签人员
            QueryWrapper<ZrSimulate> hqew=new QueryWrapper<>();
            hqew.eq("flow_id",projectWorkFlowList.get(i).getId());
            List<ZrSimulate> hqList = zrSimulateService.list(hqew);
            //处理用户
            setHqUser(hqList);
            projectWorkFlowList.get(i).setHqUsers(hqList);
            if(map.get(projectWorkFlowList.get(i).getRowIndex())==null){
                List<ProjectWorkFlow> m=new ArrayList<>();
                m.add(projectWorkFlowList.get(i));
                map.put(i,m);
            }else{
                map.get(projectWorkFlowList.get(i).getRowIndex()).add(projectWorkFlowList.get(i));
            }
        }
        List<SubWkFlow> subWkFlows=new ArrayList<>();
        for (Map.Entry<Integer, List<ProjectWorkFlow>> entry : map.entrySet()) {
            SubWkFlow subWkFlow = new SubWkFlow();
            subWkFlow.setTableData(entry.getValue());
            subWkFlows.add(subWkFlow);
        }
        notepad.getSubWk().addAll(subWkFlows);
        return ResponseInfo.success(notepad);
    }
    /**
     * 处理每个会签用户
     * @param hqList
     */
    private void setHqUser(List<ZrSimulate> hqList) {
        for (ZrSimulate hq : hqList) {
            Map<String, Object> allById = userService.getAllById(hq.getUserId());
            hq.setName(((BaseUser)allById.get("user")).getName());
            List<BaseDepartment> departLists = (List<BaseDepartment>) allById.get("departList");
            List<String> ds=new ArrayList<>();
            for (BaseDepartment department : departLists) {
                ds.add(department.getName());
            }
            hq.setDepartNames(ds.toString());
        }
    }
    @Override
    public Map<String, Object> getfullinfo(InputParam inputParam) {
        QueryWrapper<NotepadOther> qw=new QueryWrapper<>();
        qw.eq("notepad_id",inputParam.getId());
        NotepadOther o = notepadOtherService.getOne(qw);
        return ResponseInfo.success(o);
    }

    @Override
    public Map<String, Object> getCalendarDatas(InputParam inputParam) {
        DateEasy da=new DateEasy();
        if(inputParam.getGoDate()!=null){
                da=new DateEasy(inputParam.getGoDate());
        }
        DateEasy startDate=da.getFirstDayOfMonth().addDate(-7);
        DateEasy endDate=da.getLastDayOfMonth().addDate(7);
        inputParam.setStartDate(startDate.toLocalDate());
        inputParam.setEndDate(endDate.toLocalDate());
        Map<String, Object> all = this.getAll(new Notepad(), inputParam);

        List<Notepad> notepads=(List<Notepad>)all.get("rows");
        Map<String,CalendarDisplayBean> nd=new HashMap();
        for (Notepad notepad:
             notepads) {
            String key = new DateEasy(notepad.getCreateTime()).toYYYYhMMhDD();
            CalendarDisplayBean value =  nd.get(key);
            if(value==null){
                value = new CalendarDisplayBean();
                nd.put(key,value);
            }
            if(notepad.getImportantFlag()==1){
                value.importantFlag++;
            }
            if(notepad.getState()==1){
                value.totalComplete++;
            }else{
                value.totalNotComplete++;
            }
        }
        return ResponseInfo.success(nd);
    }


    @Override

    public Map<String, Object> updateSort(List<SortBean> sortList) {
        System.out.println("-------------------------gg");
        System.out.println("----------------------------" + sortList);
        sortList.forEach(item -> {
            System.out.println(item);

            UpdateWrapper<Notepad> uw = new UpdateWrapper<>();
            uw.eq("id", item.getId());
            uw.set("sort_key", item.getSortKey());

            notepadService.update(null,uw);
        });
            return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> stateChange(String id, Integer state) {
        UpdateWrapper<Notepad> uw=new UpdateWrapper<>();
        uw.eq("id",id);
        uw.set("state",state);
        this.update(uw);
        return ResponseInfo.success();
    }

    @Override
    public Map<String, Object> saveOther(Map leaderTask) {
        QueryWrapper<NotepadOther> qw=new QueryWrapper<>();
        qw.eq("notepad_Id",leaderTask.get("notepadId")+"");
        notepadOtherService.remove(qw);
        String s = JSON.toJSONString(leaderTask);
        NotepadOther notepadOther=new NotepadOther();
        notepadOther.setNotepadId(leaderTask.get("notepadId")+"");
        notepadOther.setDataJson(s);
        notepadOtherService.save(notepadOther);
        return ResponseInfo.success();
    }

    //判断备忘录是否有工序内容
    private void hasWk(Notepad temp){
        QueryWrapper qw3 = new QueryWrapper<ProjectWorkFlow>();
        qw3.eq("project_plan_id", temp.getCreater()+"-"+temp.getId());
        qw3.eq("type",1);
        List list = projectWorkFlowService.list(qw3);
        if(list.size()>0){
            temp.setFlagWk(true);
        }else {
            temp.setFlagWk(false);
        }
    }

}

